﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

namespace Xyzzer.AsyncUI
{
    public static class MediaElementExtensions
    {
        public static async Task<MediaElement> WaitForStateAsync(this MediaElement mediaElement, MediaElementState? newState = null)
        {
            if (newState != null &&
                mediaElement.CurrentState == newState.Value)
            {
                return null;
            }

            var tcs = new TaskCompletionSource<MediaElement>();
            RoutedEventHandler reh = null;

            reh = (s, e) =>
            {
                if (newState != null && mediaElement.CurrentState != newState.Value)
                {
                    return;
                }

                mediaElement.CurrentStateChanged -= reh;
                tcs.SetResult((MediaElement)s);
            };

            mediaElement.CurrentStateChanged += reh;

            return await tcs.Task;
        }
    }
}
